import axios, { type AxiosInstance } from "axios";
const BASEURL = import.meta.env.VITE_API_BASE_URL;
const TOKEN = import.meta.env.VITE_API_TOKEN;

const checkStatus = (response: any) => {
  if (response.status >= 200 && response.status < 300) {
    if (response.data.state) {
      return response.data;
    } else {
      return response.data;
    }
  }
};
class HttpRequest {
  // 请求拦截
  interceptors(instance: AxiosInstance) {
    instance.interceptors.request.use(
      (config) => {
        console.log(config);
        // 添加全局的loading..
        // 请求头携带token
        return config;
      },
      (error: any) => {
        return Promise.reject(error);
      }
    );

    //响应拦截
    instance.interceptors.response.use(
      (res) => {
        //返回数据
        const { data } = res;
        console.log("返回数据处理", res);
        return data;
      },
      (error: any) => {
        console.log("error==>", error);
        return Promise.reject(error);
      }
    );
  }

  request(url: string, method: string, data: any, responseType?: any) {
    const token = TOKEN;

    // 默认headers配置
    const headers = {
      Accept: "application/json",
      "Authorization": `Bearer ${token}`,
    };

    const instance = axios.create({
      headers,
      timeout: 10000,
      baseURL: BASEURL,
      responseType: responseType,
      withCredentials: true,
    });

    switch (method) {
      case "get":
        data = { params: data };
        break;
      default:
        data = data;
    }

    return instance({ url, method, data })
      .then(checkStatus)
      .then((data) => data)
      .catch((err) => {
        return err;
      });
  }
}

const http = new HttpRequest();

export default http;
